package com.broadcaster.broadcaster.core;


import com.broadcaster.broadcaster.core.tool.PostProcessors;
import com.broadcaster.broadcaster.core.tool.TinyApplicationContext;
import lombok.extern.slf4j.Slf4j;
import org.springframework.util.ReflectionUtils;

import java.lang.reflect.Method;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

/**
*
*
*
* m分布式map，需依赖于redis,只用于单体架构变更为分分布式，由于内部太多Map缓存需要更新
*
* 注意使用
*
* */
@Slf4j
public class BroadcasterServer {

        public  static Map<String,Integer> versionMap=new ConcurrentHashMap<>();

        public  void  doMap(String message){
            try {
                System.out.println(message);
                String doMesName=message.replace("\"","");
                String classzName=doMesName.split(",")[0];
                String methodName=doMesName.split(",")[1];
                System.out.println(classzName+methodName);
                if(!PostProcessors.mappingMap.containsKey(classzName+methodName)){
                    log.info("找不到该路径{}",classzName+","+methodName);
                    return;
                }
                doMesName=PostProcessors.mappingMap.get(classzName+methodName);
                classzName=doMesName.split(",")[0];
                methodName=doMesName.split(",")[1];
                Class clazz=Class.forName(classzName);
                if(!versionMap.containsKey(classzName+methodName)){
                    /**
                     *
                     * 不需要广播-----
                     *
                     * */
                    versionMap.put(classzName+methodName,1);
                }
                springInvokeMethod(clazz,methodName,null);
            }catch (Exception e){
                  e.printStackTrace();
            }
        }


    /**
     * 根据 服务名称 ，方法名 反射调用  spring bean 中的 方法
     * @param serviceName 服务名
     * @param methodName 方法名
     * @param params 参数
     * @return
     * @throws Exception
     */
    public static Object springInvokeMethod(Class serviceName, String methodName, Object[] params) throws Exception {
        Object service = TinyApplicationContext.getBean(serviceName);
        Class<? extends Object>[] paramClass = null;
        if (params != null) {
            int paramsLength = params.length;
            paramClass = new Class[paramsLength];
            for (int i = 0; i < paramsLength; i++) {
                paramClass[i] = params[i].getClass();
            }
        }
        // 找到方法
        Method method = ReflectionUtils.findMethod(service.getClass(), methodName, paramClass);
        //
        if(serviceName.getMethod(methodName).getAnnotation(Consumer.class)!=null){
            Object o= ReflectionUtils.invokeMethod(method, service, params);
            return o;
        }else {
            log.info("只是广播端{}",serviceName.getName()+","+methodName);
        }
        return null;
    }





}
